//
//  WYVIPController.m
//  Boss
//
//  Created by admin on 2018/7/9.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYVIPController.h"
#import "WYVIPCollectionViewCell.h"
#import "WYVipList.h"
#import "WYPayController.h"
#import "WYVIPModel.h"
#import "NSDictionary+ExchangeJson.h"
#import "WXApi.h"
#import "WYUserMessage.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WYPayAlertTooler.h"
#import "WYVipComentModel.h"
@interface WYVIPController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) IBOutlet UIView *mainView;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;

@property (strong, nonatomic) IBOutlet UIView *backView;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *collectionViewHeight;

@property (nonatomic,strong)WYPayController *payVC;

@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)NSString *vipID;
@property (nonatomic,strong)NSString *timeType;
@property (nonatomic,strong)NSString *money;

@property (strong, nonatomic) IBOutlet UIView *VipView;
@property (strong, nonatomic) IBOutlet UIImageView *userImageView;
@property (strong, nonatomic) IBOutlet UILabel *vipLevel;
@property (strong, nonatomic) IBOutlet UILabel *dateTimeLabel;
@property (strong, nonatomic) IBOutlet UIImageView *goldImageView;
@property (nonatomic,strong)WYUserMessage *userMessage;

@property (strong, nonatomic) IBOutlet UILabel *userName;

@property (strong, nonatomic) IBOutlet UIButton *buyBtn;

@property (nonatomic,strong) NSMutableArray *descArray;

@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) IBOutlet UILabel *label1;
@property (strong, nonatomic) IBOutlet UILabel *label2;
@property (strong, nonatomic) IBOutlet UILabel *label3;

@property (nonatomic,strong) NSMutableArray *commentArray;


@property (strong, nonatomic) IBOutlet UIView *silverView;

@property (strong, nonatomic) IBOutlet UIView *goldView;

@property (strong, nonatomic) IBOutlet UIView *diamondsView;

@property (strong, nonatomic) IBOutlet UIView *mainScrollView;




@end

@implementation WYVIPController
-(NSMutableArray *)commentArray
{
    if (!_commentArray) {
        _commentArray = [[NSMutableArray alloc]init];
    }
    return _commentArray;
}
-(NSMutableArray *)descArray
{
    if (!_descArray) {
        _descArray = [[NSMutableArray alloc]init];
    }
    return _descArray;
}





-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
     [self wr_setNavBarBackgroundAlpha:0];
    [self loadData];
    [self loadUserData];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WXPaySucess:) name:@"WXPaySuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AliPayResult:) name:@"AlipayResult" object:nil];
    
    [self loadDesc];
    
}

-(void)loadDesc
{
    WEAKSELF
    [WYHttpServer getVipCommentSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf.commentArray addObjectsFromArray:[WYVipComentModel getVipComentModelFromJson:response[@"result"]]];
            [weakSelf upDesc];
        }
        
        
    }];
    
    
}


-(void)upDesc
{
    for (WYVipComentModel *vip in self.commentArray) {
        if ([vip.vipId isEqualToString:@"10"]) {
            NSString *str = [vip.Comment stringByReplacingOccurrencesOfString:@";" withString:@"\n"];
            NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
            paragraphStyle.lineSpacing = 10;
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
            self.label1.attributedText = [[NSAttributedString alloc] initWithString:str attributes:attributes];
        }
        if ([vip.vipId isEqualToString:@"20"]) {
            NSString *str = [vip.Comment stringByReplacingOccurrencesOfString:@";" withString:@"\n"];
            NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
            paragraphStyle.lineSpacing = 10;
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
            self.label2.attributedText = [[NSAttributedString alloc] initWithString:str attributes:attributes];
        }
        if ([vip.vipId isEqualToString:@"30"]) {
            NSString *str = [vip.Comment stringByReplacingOccurrencesOfString:@";" withString:@"\n"];
            NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
            paragraphStyle.lineSpacing = 10;
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
            self.label3.attributedText = [[NSAttributedString alloc] initWithString:str attributes:attributes];
            
            
            
        }
        
    }
    
    self.label1.font = kFontSystemBIgger2(12);
    self.label2.font = kFontSystemBIgger2(12);
    self.label3.font = kFontSystemBIgger2(12);
    
    [self.mainView layoutIfNeeded];
    self.mainView.frame = CGRectMake(0, 0, kScreenWidth, self.label1.frame.size.height+self.label2.frame.size.height+self.label3.frame.size.height+300+600);
    [self.scrollView setContentSize:self.mainView.size];
    
    
    
    
}
-(void)AliPayResult:(NSNotification *)noc
{
    NSDictionary *dic =noc.object[@"result"];
    NSUInteger status = [dic[@"resultStatus"] integerValue];
    if (status==9000) {
        [self loadUserData];
    }else{
        
    }
}
-(void)loadUserData
{
    WEAKSELF
    [WYHttpServer getUserMessageSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        
        if (success) {
            weakSelf.userMessage = [WYUserMessage getUserMessageFromJson:response[@"result"]];
            [WYStoreModule storeUserMessage:weakSelf.userMessage];
            [weakSelf updateUI];
        }
        
    }];
}
-(void)updateUI
{
    if ([self.userMessage.vipId isEqualToString:@"10"]) {
        self.vipLevel.text = @"当前会员：白银会员";
        //self.dateTimeLabel.text = [NSString stringWithFormat:@"到期时间：%@",self.userMessage.vipEndTime];
        self.goldImageView.image = [UIImage imageNamed:@"silver"];
        [self.userImageView sd_setImageWithURL:[NSURL URLWithString:self.userMessage.url]];
        self.VipView.hidden = NO;
        self.userName.text = self.userMessage.userName;
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSDate *date = [dateFormatter dateFromString:self.userMessage.vipEndTime];
        NSLog(@"%@",date);
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        
        NSString *str = [dateFormatter stringFromDate:date];
        NSLog(@"%@",str);
        self.dateTimeLabel.text = [NSString stringWithFormat:@"到期时间：%@",str];
        
        
        
    }
    if ([self.userMessage.vipId isEqualToString:@"20"]) {
        self.vipLevel.text = @"当前会员：黄金会员";
        self.dateTimeLabel.text = [NSString stringWithFormat:@"到期时间：%@",self.userMessage.vipEndTime];
        self.goldImageView.image = [UIImage imageNamed:@"gold"];
        [self.userImageView sd_setImageWithURL:[NSURL URLWithString:self.userMessage.url]];
        self.userName.text = self.userMessage.userName;
        self.VipView.hidden = NO;
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSDate *date = [dateFormatter dateFromString:self.userMessage.vipEndTime];
        NSLog(@"%@",date);
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        
        NSString *str = [dateFormatter stringFromDate:date];
        NSLog(@"%@",str);
        self.dateTimeLabel.text = [NSString stringWithFormat:@"到期时间：%@",str];        
    }
    
    if ([self.userMessage.vipId isEqualToString:@"30"]) {
        self.vipLevel.text = @"当前会员：钻石会员";
        self.dateTimeLabel.text = [NSString stringWithFormat:@"到期时间：%@",self.userMessage.vipEndTime];
        self.goldImageView.image = [UIImage imageNamed:@"BOSS_VIP_Diamonds"];
        [self.userImageView sd_setImageWithURL:[NSURL URLWithString:self.userMessage.url]];
        self.userName.text = self.userMessage.userName;
        self.VipView.hidden = NO;
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSDate *date = [dateFormatter dateFromString:self.userMessage.vipEndTime];
        NSLog(@"%@",date);
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        
        NSString *str = [dateFormatter stringFromDate:date];
        NSLog(@"%@",str);
        self.dateTimeLabel.text = [NSString stringWithFormat:@"到期时间：%@",str];
    }
    
    if ([self.userMessage.vipId isEqualToString:@"0"]) {
        self.VipView.hidden = YES;
    }
    
}


-(void)WXPaySucess:(NSNotification *)noc
{
    [self showSucess];
    [self loadUserData];
    //[self toast:@"购买成功"];
  //  int64_t delayInSeconds = 2.0; // 延迟的时间
    
    /*
     *  delta:
     *
     *  @parameter 1.时间参照，从此刻开始计时
     *  @parameter 2.延时多久，此处为秒级，还有纳秒等: 10ull * NSEC_PER_MSEC
     */
    
//    __weak typeof(self)weakSelf = self;
//
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [weakSelf.navigationController popViewControllerAnimated:YES];
//    });
    
    
    
}


-(void)loadData
{
    WEAKSELF
    [WYHttpServer getVipListSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            NSArray *array = [WYVipList getVipListFromJson:response[@"result"]];
            for (WYVipList *list in array) {
                if ([list.id isEqualToString:@"10"]) {
                    [weakSelf.dataArray addObject:list.monthMoney];
                    [weakSelf.dataArray addObject:list.yearMoney];
                    [weakSelf.descArray addObject:list];
                }
                if ([list.id isEqualToString:@"20"]) {
                    [weakSelf.dataArray addObject:list.monthMoney];
                    [weakSelf.dataArray addObject:list.yearMoney];
                    [weakSelf.descArray addObject:list];
                }
                if ([list.id isEqualToString:@"30"]) {
                    [weakSelf.dataArray addObject:list.monthMoney];
                    [weakSelf.dataArray addObject:list.yearMoney];
                    [weakSelf.descArray addObject:list];
                }
            
            }
            [weakSelf reloadCollectionView];
            
        }
    }];
}
-(void)reloadCollectionView
{
    [self.collectionView reloadData];
    self.collectionViewHeight.constant = self.collectionView.collectionViewLayout.collectionViewContentSize.height;
    
}
- (IBAction)buyAction:(id)sender {
    
//    [self showError];
//    return;
    
    if (!self.vipID.length) {
        [self toast:@"请选择会员类别"];return;
    }
    WYPayController *pvc = [[WYPayController alloc]init];
    self.payVC = pvc;
    
//    pvc.payMoney.text = [NSString stringWithFormat:@"支付金额：¥%@",self.money];
//    self.payVC.payMoney.text = [NSString stringWithFormat:@"支付金额：¥%@",self.money];
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.maskView];
    [[UIApplication sharedApplication].keyWindow addSubview:pvc.view];
    pvc.view.frame = CGRectMake(0, kScreenHeight-370, kScreenWidth, 370);
    WEAKSELF
    pvc.exit = ^(NSString *name) {
        [weakSelf.payVC.view removeFromSuperview];
        [weakSelf.maskView removeFromSuperview];
    };
    pvc.complete = ^(NSString *name, NSString *value) {
        [weakSelf.payVC.view removeFromSuperview];
        [weakSelf.maskView removeFromSuperview];
        [weakSelf buyVIPWithType:name];
        //[weakSelf showLoading:@""];
        
    };
    [pvc setMoney:[NSString stringWithFormat:@"%.2f",self.money.floatValue/1000.0]];
}
-(void)buyVIPWithType:(NSString *)type
{
    WEAKSELF
    [WYHttpServer buyVipWithVipID:self.vipID WtihTimeType:self.timeType WithPayType:type SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            if ([type isEqualToString:@"2"]) {
                //NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response[@"result"] options:NSJSONReadingMutableContainers error:NULL];
                NSString *jsonStr = response[@"result"];
                NSDictionary *dic =  [NSDictionary dictionaryWithJsonString:jsonStr];
                
                [weakSelf goToWechat:dic];
            }
            if ([type isEqualToString:@"1"]) {
                NSString *orderString = response[@"result"];
                [weakSelf gotoAliPay:orderString];
            }
            
            if ([type isEqualToString:@"3"]) {
                [weakSelf showSucess];
            }
            
            
        }else{
            if ([type isEqualToString:@"3"]) {
                [weakSelf showError];
            }
            
            
            
            
            //[weakSelf toast:errorMessage];
        }
        
        
        
    }];
}
-(void)goToWechat:(NSDictionary *)wechatPayDic
{
    PayReq *req = [[PayReq alloc] init];
    req.openID = [wechatPayDic objectForKey:@"appid"];
    req.partnerId = [wechatPayDic objectForKey:@"partnerid"];
    req.prepayId = [wechatPayDic objectForKey:@"prepayid"];
    // req.package = @"WXpay";
    req.package = [wechatPayDic objectForKey:@"package"];
    req.nonceStr = [wechatPayDic objectForKey:@"noncestr"];
    req.timeStamp = [[wechatPayDic objectForKey:@"timestamp"] intValue];
    req.sign = [wechatPayDic objectForKey:@"sign"];
    [WXApi sendReq:req];
}

-(void)gotoAliPay:(NSString *)orderString
{
    NSLog(@"%@",orderString);
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:@"BOSS" callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
    }];
    
    
}


-(void)setupUI
{
    self.mainScrollView.width = kScreenWidth;
    self.mainScrollView.height = 1100;
    [self.scrollView addSubview:self.mainScrollView];
    self.scrollView.contentSize = self.mainScrollView.size;
    
//    self.silverView.width = kScreenWidth-20;
//    self.silverView.height = kScreenHeight;
//    
//    self.goldView.width = kScreenWidth-20;
//    self.goldView.height = kScreenHeight;
//    
//    self.diamondsView.width = kScreenWidth-20;
//    self.diamondsView.height = kScreenHeight;
    
    [self.mainScrollView addSubview:self.silverView];
    [self.mainScrollView addSubview:self.goldView];
    [self.mainScrollView addSubview:self.diamondsView];
    
    self.silverView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.goldView.frame = CGRectMake(0, kScreenWidth, kScreenWidth, kScreenHeight);
    self.diamondsView.frame = CGRectMake(0, kScreenWidth*2, kScreenWidth, kScreenHeight);
    
    
//    [self.backView setCornerRadius:10.f];
//    self.collectionView.delegate = self;
//    self.collectionView.dataSource = self;
//    [self.userImageView setCornerRadius:20.f];
//    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
//    CGFloat itemW = (kScreenWidth-32-20)/2;
//
//    layout.itemSize=CGSizeMake(itemW, itemW*0.55);
//    //横向最小距离
//    layout.minimumInteritemSpacing=10.0f;
//    layout.minimumLineSpacing=10.0f;
//    //cell距离上  左  下 右 的距离
//    layout.sectionInset=UIEdgeInsetsMake(10, 10, 10, 10);
//    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
//    [self.collectionView setCollectionViewLayout:layout];
//
//    [self.collectionView registerNib:[UINib nibWithNibName:@"WYVIPCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"WYVIPCollectionViewCell"];
//    if (@available(iOS 11.0, *)){
//        [self.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
//    }
//
//    self.navigationItem.title = @"会员";
//
//    [self wr_setNavBarShadowImageHidden:YES];
//    self.scrollView.delegate = self;
//   // [self wr_setNavBarShadowImageHidden:YES];
//    self.tableView.dataSource = self;
//    self.tableView.delegate = self;
//
    
    
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.descArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    return 12;
    
    
}

//-(void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if (scrollView == self.scrollView) {
//        CGFloat offsetY = scrollView.contentOffset.y;
//        if (offsetY > 88) {
//            CGFloat alpha = (offsetY - 88) / 88;
//            [self wr_setNavBarBackgroundAlpha:alpha];
//            [self wr_setNavBarTintColor:[[UIColor whiteColor] colorWithAlphaComponent:alpha]];
//            [self wr_setNavBarTitleColor:[[UIColor whiteColor] colorWithAlphaComponent:alpha]];
//        }else{
//            [self wr_setNavBarBackgroundAlpha:0];
//            [self wr_setNavBarTintColor:[UIColor whiteColor]];
//            [self wr_setNavBarTitleColor:[UIColor whiteColor]];
//
//        }
//    }
//}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WYVIPCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WYVIPCollectionViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell =[[NSBundle mainBundle]loadNibNamed:@"WYVIPCollectionViewCell" owner:nil options:nil].firstObject;
    }
    if (indexPath.item%2==0) {
        cell.giveImageView.hidden = YES;
    }else{
        cell.giveImageView.hidden = NO;
    }
    if (indexPath.row==0) {
        cell.timeLabel.text = @"1个月 白银会员";
    }
    if (indexPath.row==1) {
        cell.timeLabel.text = @"10个月 白银会员";
    }
    if (indexPath.row==2) {
        cell.timeLabel.text = @"1个月 黄金会员";
    }
    if (indexPath.row==3) {
        cell.timeLabel.text = @"10个月 黄金会员";
    }
    if (indexPath.row==4) {
         cell.timeLabel.text = @"1个月 钻石会员";
    }
    if (indexPath.row==5) {
         cell.timeLabel.text = @"10个月 钻石会员";
    }
    
    
    
    
    NSString *str = self.dataArray[indexPath.item];
    cell.moneyLabel.text =[NSString stringWithFormat:@"%.2f",str.floatValue/1000.0];
    cell.backgroundColor = [UIColor hexStringToColor:@"#ffffff" alpha:1.0];
    [cell setBorderWithWidth:kLineHeight andColor:[UIColor hexStringToColor:@"#e6e6e6" alpha:1.0f]];
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    WYVIPCollectionViewCell *cell =(WYVIPCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor hexStringToColor:@"#fffaf2" alpha:1.0];
    [cell setBorderWithWidth:kLineHeight andColor:kColorMainColor];
    NSLog(@"点击了一个cell");
    
    if (indexPath.row==0) {
        self.vipID = @"10";
        self.timeType = @"1";
    }
    if (indexPath.row==1) {
        self.vipID = @"10";
        self.timeType = @"2";
    }
    if (indexPath.row==2) {
        self.vipID = @"20";
        self.timeType = @"1";
    }
    if (indexPath.row==3) {
        self.vipID = @"20";
        self.timeType = @"2";
    }
    if (indexPath.row==4) {
        self.vipID = @"30";
        self.timeType = @"1";
    }
    if (indexPath.row==5) {
        self.vipID = @"30";
        self.timeType = @"2";
    }
    
    
    self.money = self.dataArray[indexPath.row];
    
    
    
    
    
    
    
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    WYVIPCollectionViewCell *cell =(WYVIPCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor hexStringToColor:@"#ffffff" alpha:1.0];
    [cell setBorderWithWidth:kLineHeight andColor:[UIColor hexStringToColor:@"#e6e6e6" alpha:1.0f]];
    
    
    NSLog(@"取消选中了一个cll");
}


-(void)showSucess
{
    WEAKSELF
    [[WYPayAlertTooler sharedInstance] showAlertTitle:@"付款成功啦" message:@"" imageName:@"pay_success_icon" btnTitles:@"我知道了" btnClicked:^(NSInteger index) {
       // NSLog(@"%ld",index);
        [weakSelf loadUserData];
    }];
}
-(void)showError
{
    [[WYPayAlertTooler sharedInstance] showAlertTitle:@"支付失败咯" message:@"支付遇到问题，请尝试重新支付" imageName:@"pay_error_icon" btnTitles:@[@"放弃",@"重新支付"] btnClicked:^(NSInteger index) {
        NSLog(@"%ld",index);
    }];
}












@end
